Page({
  data: {
    tasks: [], // 存储当前登录工人的任务
    newTasks: [],
    taskName: '',
    taskTime: '',
    taskNote: ''
  },

  onLoad(options) {
    console.log('Page onLoad');
    this.getTasksByWorkerId(); // 获取当前登录工人的任务
    this.batchAddTasksToDatabase();
  },

  onReady() {
    console.log('Page onReady');
  },

  getTasksByWorkerId() {
    const db = wx.cloud.database();
    const today = this.getTodayDate();
    const userId = this.getLoginUserId(); // 获取当前登录用户的工人ID
    db.collection('tasks').where({
      workerId: userId,
      date: today
    }).get({
      success: res => {
        console.log('从数据库读取任务数据成功', res.data);
        this.setData({
          tasks: res.data
        });
      },
      fail: err => {
        console.error('从数据库读取任务数据失败', err);
      }
    });
  },

  getLoginUserId() {
    const app = getApp();
    return app.globalData.userId;
  },

  getWorkerName() {
    const app = getApp();
    return app.globalData.userNickname;
  },

  submitTask(event) {
    const { taskIndex } = event.currentTarget.dataset;
    const tasks = this.data.tasks.map((task, i) => {
      if (i === taskIndex) {
        console.log('Marking task as completed:', task);
        return { ...task, completed: true };
      }
      return task;
    });
    this.setData({
      tasks
    });
    this.saveTasksDataToDatabase(tasks);
  },

  acceptTask(event) {
    const { taskIndex } = event.currentTarget.dataset;
    const tasks = this.data.tasks.map((task, i) => {
      if (i === taskIndex) {
        return { ...task, accepted: true };
      }
      return task;
    });
    this.setData({
      tasks
    });

    wx.chooseImage({
      count: 2, // 至少选择两张图片
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (res.tempFilePaths.length < 2) {
          wx.showToast({
            title: '请至少上传两张图片',
            icon: 'none'
          });
          return;
        }
        setTimeout(() => {
          const tasks = this.data.tasks.map((task, i) => {
            if (i === taskIndex) {
              console.log('Updating photos for task:', task);
              return { ...task, accepted: true, photos: res.tempFilePaths };
            }
            return task;
          });
          this.setData({
            tasks
          });

          this.saveTasksDataToDatabase(tasks);

          wx.showToast({
            title: '任务验收成功',
            icon: 'success'
          });
        }, 100); // 添加 100ms 延迟
      }
    });
  },

  revokeSubmitTask(event) {
    const { taskIndex } = event.currentTarget.dataset;
    const tasks = this.data.tasks.map((task, i) => {
      if (i === taskIndex) {
        return { ...task, completed: false };
      }
      return task;
    });
    this.setData({
      tasks
    });
    this.saveTasksDataToDatabase(tasks);
  },

  revokeAcceptTask(event) {
    const { taskIndex } = event.currentTarget.dataset;
    const tasks = this.data.tasks.map((task, i) => {
      if (i === taskIndex) {
        return { ...task, accepted: false, photos: [] };
      }
      return task;
    });
    this.setData({
      tasks
    });
    this.saveTasksDataToDatabase(tasks);
  },

  deleteNewTask(event) {
    console.log('deleteNewTask called', event);
    const taskIndex = event.currentTarget.dataset.taskIndex;
    console.log('Task index to delete:', taskIndex);
    const taskToDelete = this.data.newTasks[taskIndex];
  
    if (!taskToDelete._id) {
      console.error('任务没有 _id，无法删除');
      wx.showToast({
        title: '任务删除失败，任务没有 _id',
        icon: 'none'
      });
      return;
    }
  
    // 从页面数据中删除任务
    let newTasks = this.data.newTasks.filter((task, index) => index !== taskIndex);
    this.setData({
      newTasks
    });
  
    // 从数据库中删除任务
    const db = wx.cloud.database();
    db.collection('tasks').doc(taskToDelete._id).remove({
      success: res => {
        console.log('任务删除成功', res);
        wx.showToast({
          title: '任务删除成功',
          icon: 'success'
        });
      },
      fail: err => {
        console.error('任务删除失败', err);
        wx.showToast({
          title: '任务删除失败',
          icon: 'none'
        });
      }
    });
  },

  onShow() {
    console.log('Page onShow');
  },

  onHide() {
    console.log('Page onHide');
  },

  onTaskNameInput(e) {
    this.setData({
      taskName: e.detail.value
    });
  },

  onTaskTimeInput(e) {
    this.setData({
      taskTime: e.detail.value
    });
  },

  onTaskNoteInput(e) {
    this.setData({
      taskNote: e.detail.value
    });
  },

  onAddTaskSubmit(event) {
    const formData = event.detail.value;
    const newTask = {
      id: Date.now(),
      name: formData.taskName,
      time: formData.taskTime,
      note: formData.taskNote,
      date: this.getTomorrowDate(), // 设置任务的日期为明天
      workerId: this.getLoginUserId(), // 获取当前登录用户的工人ID
      workerName: this.getWorkerName(),
      completed: false,
      accepted: false,
      photos: []
    };
  
    // 添加任务到数据库
    this.batchAddTasksToDatabase([newTask]);
  
    // 更新页面数据
    const newTasks = this.data.newTasks.concat(newTask);
    this.setData({
      newTasks: newTasks,
      taskName: '',
      taskTime: '',
      taskNote: ''
    });
  },

  batchAddTasksToDatabase(tasks = []) {
    const db = wx.cloud.database();
    const tasksCollection = db.collection('tasks');
    tasks.forEach((task, index) => {
      tasksCollection.add({
        data: task,
        success: res => {
          console.log('数据添加成功', res);
          // 更新任务对象，添加 _id 字段
          tasks[index]._id = res._id; // 更新任务的 _id
          this.setData({
            newTasks: tasks // 更新页面数据
          });
        },
        fail: err => {
          console.error('数据添加失败', err);
        }
      });
    });
  },

  saveTasksDataToDatabase(tasks) {
    const db = wx.cloud.database();
    tasks.forEach(task => {
      db.collection('tasks').doc(task._id).update({
        data: {
          completed: task.completed,
          accepted: task.accepted,
          photos: task.photos
        },
        success: res => {
          console.log('数据更新成功', res);
        },
        fail: err => {
          console.error('数据更新失败', err);
        }
      });
    });
  },

  getTodayDate() {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
  },

  getTomorrowDate() {
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(now.getDate() + 1); // 添加一天
    return `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-20`;
  }
});